package org.korifey.ffbdd.common.util;

/**
 * Functions of byte conversion
 * 
 * @author daivanov
 *
 */
public class ByteUtil {
	public static int byteToInt(byte b) {
		//TODO experimentary
		return b & 0xff; 
	}
	
	//Direct
	public static int twoByteToInt(byte hi, byte lo) {
		return (byteToInt(hi) << 8) + byteToInt(lo);
	}
	
	public static int halfByteToInt(byte b, boolean hi) {
		return (byteToInt(b) >> (hi ? 4 : 0)) & 0xF;  
	}
	
	public static int oneByteAndHalfToInt(byte b, int rem) {
		return (byteToInt(b) << 4) + rem;
	}
	
	public static int threeByteAndHalfToInt(byte hi, byte m, byte lo, int rem) {
		return (byteToInt(hi) << 20) + (byteToInt(m) << 12) + (byteToInt(lo) << 4) + rem;
	}
	
	
	//Reverse
	public static void intToTwoBytes(int val, byte[] arr, int offset) {
		arr[offset] = (byte)((val >> 8) & 0xFF);
		arr[offset+1] = (byte) (val & 0xFF); 
	}
	
	public void intToHalfByte(int val, byte[] arr, int offset, boolean hi) {
		arr[offset] |= val << (hi ? 4 : 0); 
	}
	
	public static byte twoHalfsToByte(int hi, int lo) {
		return (byte)((hi << 4) | lo); 
	}
	
	public static int intToOneByteAndHalf(int val, byte[] arr, int offset) {
		arr[offset] = (byte)((val >> 4) & 0xFF);
		return val & 0xF;
	}
	
	public static int intToThreeBytesAndHalf(int val, byte[] arr, int offset) {
		arr[offset] = (byte)((val >> 20) & 0xFF);
		arr[offset+1] = (byte)((val >> 12) & 0xFF);
		arr[offset+2] = (byte)((val >> 4) & 0xFF);
		return val & 0xF;		
	}
	
	
	
	public static void main(String [] args) {
		byte b = (byte)254;
		System.out.println(b);
		System.out.println(halfByteToInt(b, true));
		System.out.println(halfByteToInt(b, false));
		
		b = (byte)65;
		System.out.println(halfByteToInt(b, true));
		System.out.println(halfByteToInt(b, false));
	}
}
